<?php


namespace App\Http\Controllers\Estate;


use App\Http\Controllers\Controller;
use App\Models\Notice;
use Illuminate\Http\Request;

class NoticeController extends Controller
{
    public $model;

    public function __construct(){
        $this->model = new Notice();
    }

    /**
     *banner列表
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        $user = $request->user();
        $param = $request->query();
        //查询当前物业自己添加的数据
        $where['status'] = 1;
        $where['estate_id'] = $user['estate_id'];
        $whereRaw = '';
        if (isset($param['name']) && !empty($param['name'])) $where[] = ['name','like',"%{$param['name']}%"];
        if (isset($param['community_id']) && !empty($param['community_id'])) $whereRaw = 'find_in_set('.$param['community_id'].',community_id)';
        return $this->success( $this->model->getList($where ,$whereRaw,'id','desc'));
    }

    /**
     * 新增
     * @param Request $request
     * @return array
     */
    public function store(Request $request)
    {
        $data = $request->post();
        $user = $request->user();
        $data['estate_id'] = $user['estate_id'];
        $data['admin_user'] = $user['id'];
        $data['community_id'] = implode(',',$data['community_ids']);
        unset($data['community_ids']);
        if(strtotime($data['start_time'])>strtotime($data['end_time']))$this->error('结束时间不能早于开始时间!');
        return $this->model->create($data) ? $this->success('添加成功!') : $this->error('添加失败!');
    }

    /**
     * 获取详情
     * @param $id
     * @return array
     */
    public function show($id)
    {
        return $this->success( $this->model->getInfo(['id' => $id]) );
    }

    /**
     * 编辑
     * @param Request $request
     * @return array
     */
    public function update(Request $request)
    {
        $data = $request->post();
        $data['community_id'] = implode(',',$data['community_ids']);
        unset($data['community_ids']);
        unset($data['community_name']);
        if(strtotime($data['start_time'])>strtotime($data['end_time']))$this->error('结束时间不能早于开始时间!');
        return $this->model->edit( $data) ? $this->success('修改成功!') : $this->error('修改失败!');
    }

    /**
     * 删除
     * @param Request $request
     * @return array
     */
    public function destroy ($ids)
    {
        return $this->model->deletes( $ids ) ? $this->success('删除成功!') : $this->error('删除失败!');
    }

    /**
     *更改启用状态
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function edit_show(Request $request)
    {
        $id = $request->post('id');
        $is_show = $this->model->getValue(['id' => $id],'is_show') == 1 ? 0 : 1;
        return $this->model->updateByWhere(['id' => $id],['is_show' => $is_show]) ? $this->success('修改成功!') : $this->error('修改失败!');
    }
}
